﻿using System;
using System.Collections.Generic;
using System.Text;
using MySql.Data.MySqlClient;

namespace AppMain
{
    public class SqlMgr : Singleton<SqlMgr>
    {

        public void init() { }

        MySqlConnection connection;
        protected override void initialize()
        {
            connectMySql();
        }

        public int insert(string sql)
        {
            //插入一条数据
            //"insert into tb_role_info(roleid,nickname,level) values(1003,'wang',99)"
            MySqlCommand insertCmd = new MySqlCommand(sql, connection);
            return insertCmd.ExecuteNonQuery();
        }

        public int update(string sql)
        {
            //更新
            //"update tb_role_info set nickname='zhang',level='888' where roleid='1003' "
            MySqlCommand updateCmd = new MySqlCommand(sql, connection);
            return updateCmd.ExecuteNonQuery();
        }

        public int delete(string sql)
        {
            //删除
            //"delete from tb_role_info where roleid='1003' "
            MySqlCommand deleteCmd = new MySqlCommand(sql, connection);
            return deleteCmd.ExecuteNonQuery();
        }

        public MySqlDataReader select(string sql)
        {
            //查
            //"select * from tb_role_info where roleid='1001' "
            MySqlCommand selectCmd = new MySqlCommand(sql, connection);
            MySqlDataReader reader = selectCmd.ExecuteReader();
            return reader;
        }

        public bool has(string sql)
        {
            //查
            //"select * from tb_role_info where roleid='1001' "
            MySqlCommand selectCmd = new MySqlCommand(sql, connection);
            MySqlDataReader reader = selectCmd.ExecuteReader();
            bool result = reader.Read();
            reader.Close();
            return result;
        }

        void connectMySql()
        {
            //database = 数据库名称
            String connetStr = "server=127.0.0.1;port=3306;user=root;password=chuyin01; database=my_game_db;";
            connection = new MySqlConnection(connetStr);
            try
            {
                connection.Open();//打开通道，建立连接，可能出现异常,使用try catch语句
                Console.WriteLine("已经建立数据库连接");
                //Console.WriteLine(has("select *from tb_account_info where username='cocotang'"));
                //Console.WriteLine(has("select *from tb_account_info where username='mmp'"));
            }
            catch (MySqlException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

    }
}
